package carassius.GUI;

import carassius.DAL.ActionRow;
import carassius.DAL.AquariumRow;
import carassius.DAL.Database;
import carassius.DAL.WaterConditionRow;
import carassius.DAL.WaterMeasurementListRow;
import carassius.DAL.WaterMeasurementRow;
import carassius.DAL.WaterRefreshmentRow;
import java.awt.Frame;
import java.sql.Date;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.ResourceBundle;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author siebz0r
 */
public class WaterActionForm
		extends javax.swing.JDialog
{
	//<editor-fold defaultstate="collapsed" desc="Fields">
	private Date _date;
	private AquariumRow _aquariumRow;
	private ActionRow _actionRow;
	private Action _action;
	//</editor-fold>

	//<editor-fold defaultstate="collapsed" desc="Constructors">
	public WaterActionForm(Frame parent, WaterMeasurementRow row,
						   AquariumRow aquariumRow, Date date)
	{
		this(parent, date, aquariumRow, Action.WaterMeasurement);
	}

	public WaterActionForm(Frame parent, WaterMeasurementRow row)
	{
		this(parent, row.getDate(), row.getAquarium(), Action.WaterMeasurement);
		fillWaterConditionsTable();

		try
		{
			ArrayList<WaterMeasurementListRow> measurementListRows = Database.getWaterMeasurementListTable().getByMeasurementID(row.getId());
			DefaultTableModel model = (DefaultTableModel) uxWaterValuesTable.getModel();

			boolean added = false;
			for (WaterMeasurementListRow r : measurementListRows)
			{
				for (int i = 0; i < model.getRowCount(); i++)
				{
					if (r.getWaterConditionRow().equals(model.getValueAt(i, 0)))
					{
						model.setValueAt(r, i, 0);
						model.setValueAt(r.getValue(), i, 1);
						added = true;
						break;
					}
				}
				if (!added)
				{
					model.addRow(new Object[]
							{
								r.getWaterConditionRow().getName(), r.getValue()
							});
				}
				added = false;
			}

		}
		catch (SQLException ex)
		{
			uxSaveButton.setEnabled(false);
			StringBuilder msg = new StringBuilder();
			msg.append(ResourceBundle.getBundle("carassius.resources.Messages").getString("FetchWaterConditionsError"));
			msg.append("\n");
			msg.append(ResourceBundle.getBundle("carassius.resources.Messages").getString("SaveIsDisabledMessage"));

			JOptionPane.showMessageDialog(this,
					msg.toString(),
					ResourceBundle.getBundle("carassius.resources.Messages").getString("FetchWaterConditionsErrorTitle"),
					JOptionPane.ERROR_MESSAGE);
		}
		if (row instanceof WaterMeasurementRow)
		{
			_actionRow = row;
			uxCommentTextArea.setText(row.getComment());
			setTitle(ResourceBundle.getBundle("carassius/GUI/resources/WaterActionForm").getString("title.edit.WaterMeasurement"));
		}
		else
		{
			setTitle(ResourceBundle.getBundle("carassius/GUI/resources/WaterActionForm").getString("title.add.WaterMeasurement"));
		}
	}

	public WaterActionForm(Frame parent, WaterRefreshmentRow row,
						   AquariumRow aquariumRow, Date date)
	{
		this(parent, date, aquariumRow, Action.WaterRefreshment);
	}

	public WaterActionForm(Frame parent, WaterRefreshmentRow row)
	{
		this(parent, row.getDate(), row.getAquarium(), Action.WaterRefreshment);

		if (row instanceof WaterRefreshmentRow)
		{
			_actionRow = row;
			uxCommentTextArea.setText(row.getComment());
			setTitle(ResourceBundle.getBundle("carassius/GUI/resources/WaterActionForm").getString("title.edit.WaterRefreshment"));
		}
		else
		{
			setTitle(ResourceBundle.getBundle("carassius/GUI/resources/WaterActionForm").getString("title.add.WaterRefreshment"));
		}
	}

	private WaterActionForm(Frame parent, Date date, AquariumRow aquariumRow,
							Action action)
	{
		super(parent, true);
		_date = date;
		_aquariumRow = aquariumRow;
		_action = action;
		initComponents();

		uxAquariumLabel.setText(aquariumRow.getName());
		uxDateLabel.setText(date.toString());
	}
	//</editor-fold>

	//<editor-fold defaultstate="collapsed" desc="Private Methods">
	private void fillWaterConditionsTable()
	{
		try
		{
			DefaultTableModel model = (DefaultTableModel) uxWaterValuesTable.getModel();

			for (WaterConditionRow row : Database.getWaterConditionTable().getAll())
			{
				model.addRow(new Object[]
						{
							row, null
						});
			}
		}
		catch (SQLException ex)
		{
			//todo: handle
		}
	}

	private void saveAsWaterMeasurement()
	{
		String comment = uxCommentTextArea.getText().trim();
		boolean result = false;

		if (_actionRow instanceof WaterMeasurementRow)
		{
			if (result = (comment.equals(_actionRow.getComment()) || _actionRow.setComment(comment)))
			{
				result = saveWaterConditions();
			}
		}
		else
		{
			try
			{
				_actionRow = (WaterMeasurementRow) Database.getWaterMeasurementTable().add(
						_date,
						comment,
						_aquariumRow);
				if (_actionRow != null)
				{
					result = saveWaterConditions();
				}
			}
			catch (SQLException ex)
			{
				System.out.println(ex.toString());
				result = false;
			}
		}
		if (result)
		{
			JOptionPane.showMessageDialog(this,
					ResourceBundle.getBundle("carassius.resources.Messages").getString("WaterMeasurementSaved"),
					ResourceBundle.getBundle("carassius.resources.Messages").getString("WaterMeasurementSavedTitle"),
					JOptionPane.INFORMATION_MESSAGE);
			dispose();
		}
		else
		{
			JOptionPane.showMessageDialog(this,
					ResourceBundle.getBundle("carassius.resources.Messages").getString("SaveWaterMeasurementError"),
					ResourceBundle.getBundle("carassius.resources.Messages").getString("SaveWaterMeasurementErrorTitle"),
					JOptionPane.ERROR_MESSAGE);
		}
	}

	private void saveAsWaterRefreshment()
	{
		String comment = uxCommentTextArea.getText().trim();
		boolean result = false;

		if (_actionRow instanceof WaterRefreshmentRow)
		{
			result = (comment.equals(_actionRow.getComment()) || _actionRow.setComment(comment));
		}
		else
		{
			try
			{
				_actionRow = (WaterRefreshmentRow) Database.getWaterRefreshmentTable().add(_date, comment, _aquariumRow);
				result = _actionRow != null;
			}
			catch (SQLException ex)
			{
				System.out.println(ex.toString());
				result = false;
			}
		}
		if (result)
		{
			JOptionPane.showMessageDialog(this,
					ResourceBundle.getBundle("carassius.resources.Messages").getString("WaterRefreshmentSaved"),
					ResourceBundle.getBundle("carassius.resources.Messages").getString("WaterRefreshmentSavedTitle"),
					JOptionPane.INFORMATION_MESSAGE);
			dispose();
		}
		else
		{
			JOptionPane.showMessageDialog(this,
					ResourceBundle.getBundle("carassius.resources.Messages").getString("SaveWaterRefreshmentError"),
					ResourceBundle.getBundle("carassius.resources.Messages").getString("SaveWaterRefreshmentErrorTitle"),
					JOptionPane.ERROR_MESSAGE);
		}
	}

	private boolean saveWaterConditions()
	{
		DefaultTableModel model = (DefaultTableModel) uxWaterValuesTable.getModel();
		boolean result = false;
		for (int i = 0; i < model.getRowCount(); i++)
		{
			Object row = model.getValueAt(i, 0);
			Double value = (Double) model.getValueAt(i, 1);
			if (row instanceof WaterMeasurementListRow)
			{
				WaterMeasurementListRow waterMeasurementListRow = (WaterMeasurementListRow)row;
				if (value != null)
				{
					result = (value.equals(waterMeasurementListRow.getValue()) || waterMeasurementListRow.setValue(value));
				}
				else
				{
					try
					{
						result = Database.getWaterMeasurementListTable().delete(waterMeasurementListRow);
						model.setValueAt(waterMeasurementListRow.getWaterConditionRow(), i, 0);
					}
					catch (SQLException ex)
					{
						System.out.println(ex.toString());
						result = false;
					}
				}
			}
			else if (row instanceof WaterConditionRow)
			{
				try
				{
					WaterMeasurementListRow waterMeasurementListRow = Database.getWaterMeasurementListTable().add((WaterMeasurementRow) _actionRow, (WaterConditionRow) row, value);
					if (result = (waterMeasurementListRow != null))
					{
						model.setValueAt(waterMeasurementListRow, i, 0);
					}
				}
				catch (SQLException ex)
				{
					System.out.println(ex.toString());
					result = false;
				}
			}
			if (!result)
			{
				break;
			}
		}
		return result;
	}
	//</editor-fold>

	/** This method is called from within the constructor to
	 * initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is
	 * always regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        uxCommentPanel = new javax.swing.JPanel();
        uxCommentScrollPane = new javax.swing.JScrollPane();
        uxCommentTextArea = new TextAreaWithMenu();
        uxAquariumPrefixLabel = new javax.swing.JLabel();
        uxAquariumLabel = new javax.swing.JLabel();
        uxDatePrefixLabel = new javax.swing.JLabel();
        uxDateLabel = new javax.swing.JLabel();
        uxButtonPanel = new javax.swing.JPanel();
        uxSaveButton = new javax.swing.JButton();
        uxCancelButton = new javax.swing.JButton();
        if (_action == Action.WaterMeasurement)
        {
            uxWaterValuesScrollPane = new javax.swing.JScrollPane();
        }
        if (_action == Action.WaterMeasurement)
        {
            uxWaterValuesTable = new javax.swing.JTable();
            uxWaterValuesTable.putClientProperty("terminateEditOnFocusLost", true);
        }

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        getContentPane().setLayout(new java.awt.GridBagLayout());

        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("carassius/GUI/resources/WaterActionForm"); // NOI18N
        uxCommentPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(bundle.getString("uxCommentPanel.border.title"))); // NOI18N
        uxCommentPanel.setName("uxCommentPanel"); // NOI18N
        uxCommentPanel.setLayout(new java.awt.GridBagLayout());

        uxCommentScrollPane.setName("uxCommentScrollPane"); // NOI18N

        uxCommentTextArea.setColumns(20);
        uxCommentTextArea.setRows(5);
        uxCommentTextArea.setName("uxCommentTextArea"); // NOI18N
        uxCommentScrollPane.setViewportView(uxCommentTextArea);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        uxCommentPanel.add(uxCommentScrollPane, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 5);
        getContentPane().add(uxCommentPanel, gridBagConstraints);

        uxAquariumPrefixLabel.setText(bundle.getString("uxAquariumPrefixLabel.text")); // NOI18N
        uxAquariumPrefixLabel.setName("uxAquariumPrefixLabel"); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        getContentPane().add(uxAquariumPrefixLabel, gridBagConstraints);

        uxAquariumLabel.setName("uxAquariumLabel"); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(5, 0, 5, 5);
        getContentPane().add(uxAquariumLabel, gridBagConstraints);

        uxDatePrefixLabel.setText(bundle.getString("uxDatePrefixLabel.text")); // NOI18N
        uxDatePrefixLabel.setName("uxDatePrefixLabel"); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(0, 5, 5, 5);
        getContentPane().add(uxDatePrefixLabel, gridBagConstraints);

        uxDateLabel.setName("uxDateLabel"); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 5, 5);
        getContentPane().add(uxDateLabel, gridBagConstraints);

        uxButtonPanel.setName("uxButtonPanel"); // NOI18N
        uxButtonPanel.setLayout(new java.awt.GridBagLayout());

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(carassius.CarassiusApp.class).getContext().getResourceMap(WaterActionForm.class);
        uxSaveButton.setText(resourceMap.getString("uxSaveButton.text")); // NOI18N
        uxSaveButton.setName("uxSaveButton"); // NOI18N
        uxSaveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                uxSaveButtonActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTHEAST;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        uxButtonPanel.add(uxSaveButton, gridBagConstraints);

        uxCancelButton.setText(bundle.getString("uxCancelButton.text")); // NOI18N
        uxCancelButton.setName("uxCancelButton"); // NOI18N
        uxCancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                uxCancelButtonActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTHEAST;
        gridBagConstraints.insets = new java.awt.Insets(5, 0, 5, 5);
        uxButtonPanel.add(uxCancelButton, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTHEAST;
        gridBagConstraints.weightx = 1.0;
        getContentPane().add(uxButtonPanel, gridBagConstraints);

        if (_action == Action.WaterMeasurement)
        {
            uxWaterValuesScrollPane.setMaximumSize(new java.awt.Dimension(150, 32767));
            uxWaterValuesScrollPane.setName("uxWaterValuesScrollPane"); // NOI18N
            uxWaterValuesScrollPane.setPreferredSize(new java.awt.Dimension(150, 403));

            uxWaterValuesTable.setModel(new javax.swing.table.DefaultTableModel(
                new Object [][] {

                },
                new String [] {
                    "Naam", "mg/L"
                }
            ) {
                Class[] types = new Class [] {
                    java.lang.String.class, java.lang.String.class
                };
                boolean[] canEdit = new boolean [] {
                    false, true
                };

                public Class getColumnClass(int columnIndex) {
                    return types [columnIndex];
                }

                public boolean isCellEditable(int rowIndex, int columnIndex) {
                    return canEdit [columnIndex];
                }
            });
            uxWaterValuesTable.setCellSelectionEnabled(true);
            uxWaterValuesTable.setMaximumSize(new java.awt.Dimension(150, 0));
            uxWaterValuesTable.setName("uxWaterValuesTable"); // NOI18N
            uxWaterValuesTable.getColumnModel().getColumn(1).setCellRenderer(new DoubleTableCellRenderer());
            uxWaterValuesTable.getColumnModel().getColumn(1).setCellEditor(new DoubleTableCellEditor());
            uxWaterValuesScrollPane.setViewportView(uxWaterValuesTable);
            uxWaterValuesTable.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);
            uxWaterValuesTable.getColumnModel().getColumn(0).setHeaderValue(bundle.getString("uxWaterValuesTable.columnModel.title0")); // NOI18N
            uxWaterValuesTable.getColumnModel().getColumn(1).setHeaderValue(bundle.getString("uxWaterValuesTable.columnModel.title1")); // NOI18N

            gridBagConstraints = new java.awt.GridBagConstraints();
            gridBagConstraints.gridx = 2;
            gridBagConstraints.gridy = 0;
            gridBagConstraints.gridheight = 3;
            gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL;
            gridBagConstraints.ipadx = 100;
            gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
            gridBagConstraints.weighty = 1.0;
            gridBagConstraints.insets = new java.awt.Insets(5, 0, 0, 5);
            getContentPane().add(uxWaterValuesScrollPane, gridBagConstraints);
        }

        pack();
    }// </editor-fold>//GEN-END:initComponents

	private void uxSaveButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_uxSaveButtonActionPerformed
	{//GEN-HEADEREND:event_uxSaveButtonActionPerformed
		switch (_action)
		{
			case WaterMeasurement:
				saveAsWaterMeasurement();
				break;
			case WaterRefreshment:
				saveAsWaterRefreshment();
				break;
		}
}//GEN-LAST:event_uxSaveButtonActionPerformed

	private void uxCancelButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_uxCancelButtonActionPerformed
	{//GEN-HEADEREND:event_uxCancelButtonActionPerformed
		dispose();
}//GEN-LAST:event_uxCancelButtonActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel uxAquariumLabel;
    private javax.swing.JLabel uxAquariumPrefixLabel;
    private javax.swing.JPanel uxButtonPanel;
    private javax.swing.JButton uxCancelButton;
    private javax.swing.JPanel uxCommentPanel;
    private javax.swing.JScrollPane uxCommentScrollPane;
    private javax.swing.JTextArea uxCommentTextArea;
    private javax.swing.JLabel uxDateLabel;
    private javax.swing.JLabel uxDatePrefixLabel;
    private javax.swing.JButton uxSaveButton;
    private javax.swing.JScrollPane uxWaterValuesScrollPane;
    private javax.swing.JTable uxWaterValuesTable;
    // End of variables declaration//GEN-END:variables

	private enum Action
	{
		WaterMeasurement,
		WaterRefreshment
	}
}
